<template>

</template>

<script setup>
import { computed, reactive, ref, watch, watchEffect } from 'vue';
import { ChangeQuantityInShopping, DeleteShoppingData, GetShoppingCart } from '../../apis/api.js';

// 定义一个 checkedItems 数组，用于存储已勾选的商品 ID
const checkedItems = ref([]);

// 定义一个 productId 变量，用于存储商品 ID
const productId = ref();

// 定义全选变量
const checked = ref(false);

// toast
const toast = reactive({
	type: '',
	message: ''
});
// 方法
const uToastRef = ref(null);

// 定义一个 data 变量，用于存储商品数据
const data = reactive({
	product: [],
	user_id: ''
});

// 获取购物车数据的函数
const getShoppingCartData = async (userId) => {
	await GetShoppingCart(userId).then((res) => {
		if (res.msgType == 8000) {
			console.log(res);
			data.product = res.data;
			console.log(data.product);
		}
	});
};

// 通过 id 获取用户信息
watchEffect(() => {
	uni.getStorage({
		key: 'userId',
		success: async (res) => {
			data.user_id = res.data;
			console.log('获取的 userId 为：', data.user_id);
			getShoppingCartData(data.user_id);
		},
		fail: (error) => {
			console.error('获取 userId 失败：', error);
		}
	});
});

// 抛出事件，当子组件的数据修改时,让父组件取刷新
const emits = defineEmits(['refreshData']);

// 计算总金额
// 计算总金额
const totalPrice = computed(() => {
	let sum = 0;
	data.product.forEach((item) => {
		if (item.ischecked) {
			sum += parseFloat(item.price * item.quantity);
		}
	});
	return sum.toFixed(2);
});

// 计算单个商品的金额
function calculatePrice(item) {
	return (item.price * item.quantity).toFixed(2);
}

// 勾选/取消勾选商品
const checkboxChange = (item) => {
	const i = data.product.findIndex((value) => value.id === item.id);
	data.product[i].ischecked = !data.product[i].ischecked;
	const allChecked = data.product.every((v) => v.ischecked);
	if (allChecked) {
		checked.value = true;
	} else {
		checked.value = false;
	}

	// 当商品被选中时，它将其ID添加到checkedItems数组中；当商品被取消选中时，它将从数组中移除其ID
	if (data.product[i].ischecked) {
		checkedItems.value.push(item.id);
	} else {
		const index = checkedItems.value.indexOf(item.id);
		if (index !== -1) {
			checkedItems.value.splice(index, 1);
		}
	}
};

// 全选/取消全选

// 全选/取消全选
function toggleAllCheck(e) {
  // 第一次点击全选时，将 checked 的值取反，并选中或取消选中所有商品
  if (!checked.value) {
    checked.value = true;
    data.product.forEach((v) => {
      v.ischecked = true;
      if (!checkedItems.value.includes(v.id)) {
        checkedItems.value.push(v.id);
      }
    });
  } else {
    checked.value = false;
    // 取消选中所有商品，并清空 checkedItems 数组
    data.product.forEach((v) => {
      v.ischecked = false;
    });
    checkedItems.value = [];
  }
}


// 修改数量
const changeNum = (item) => {
	console.log(item);
	ChangeQuantityInShopping({
		quantity: item.quantity , //为什么加1，因为有个错误，就是每次刷新后都是小于1，不能得到正确的值
		id: item.id
	}).then((res) => {
		console.log(res);
		if (res.msgType == 8000) {
			toast.type = 'loading';
			toast.message = res.msg;
			uToastRef.value.show({ type: toast.type, message: toast.message, duration: 500 });
		} else {
			toast.type = 'error';
			toast.message = res.msg;
			uToastRef.value.show({ type: toast.type, message: toast.message, duration: 500 });
		}
	});
};

// 定义一个 computed 属性，用于判断是否所有商品都被勾选
const allChecked = computed(() => {
  return data.product.every((item) => item.ischecked);
});

// 删除购物车
const deleteShopping = () => {
  if (checkedItems.value.length > 0) {
    // 先保存当前选中的商品列表
    const selectedItems = checkedItems.value.slice();
    // 弹出确认框
    uni.showModal({
      title: '确认删除',
      content: '确定要删除选中的商品吗？',
      success: function(res) {
        if (res.confirm) {
          // 用户点击确定执行删除操作
          // 获取要删除的商品的 ID
          const deleteIds = selectedItems;
          DeleteShoppingData({
            id: deleteIds
          }).then((res) => {
            // 删除成功后更新数据
            if (res.msgType == 8000) {
              toast.type = 'success';
              toast.message = res.msg;
              uToastRef.value.show({ type: toast.type, message: toast.message, duration: 300 });
              getShoppingCartData(data.user_id);

              // 删除成功后更新选中状态和全选状态
              data.product.forEach((item) => {
                if (selectedItems.includes(item.id)) {
                  item.ischecked = false;
                }
              });
              checkedItems.value = checkedItems.value.filter((id) => !selectedItems.includes(id));
              checked.value = allChecked.value;
            } else {
              toast.type = 'error';
              toast.message = res.msg;
              uToastRef.value.show({ type: toast.type, message: toast.message, duration: 300 });
            }
          });
        }
      }
    });
  } else {
    toast.type = 'error';
    toast.message = '请选择要删除的商品';
    uToastRef.value.show({ type: toast.type, message: toast.message, duration: 300 });
  }
};
</script>

<style lang="less" scoped>
.cart_card {
	width: 100%;
	background-color: #f5f9fa;
	box-sizing: border-box;
	padding: 10rpx;
	.cart_content {
		.cart_content_card {
			width: 100%;
			height: 250rpx;
			border: 2rpx solid #ccc;
			border-radius: 5px;
			box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
			margin-bottom: 10rpx;
			background-color: #ffffff;
			display: flex;
			.cart_content_left {
				width: 40%;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 10rpx;
				.cart_content_img {
					width: 200rpx;
					height: 200rpx;
					image {
						width: 100%;
						height: 100%;
					}
				}
			}
			.cart_content_right {
				width: 60%;
				padding: 20rpx;
				.cart_content_right_top {
					.cart_content_title {
						padding: 6rpx;
					}
				}
				.cart_content_right_bottom {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 30rpx;
					.cart_content_right_price {
						color: #fa8a59;
						font-size: 36rpx;
					}
					.cart_content_right_number {
					}
				}
			}
		}
	}
}
.content {
	width: 100%;
	height: 100rpx;
	position: fixed;
	bottom: 80rpx;
	// #ifndef H5
	bottom: 5rpx;
	// #endif
	border: 2rpx solid #ccc;
	border-radius: 5px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	// margin-bottom: 10rpx;
	display: flex;
	justify-content: space-between;
	background-color: #f9f9f9;
	z-index: 1;
	.cart_submit_left {
		width: 40%;
		// border: 1px solid red;
		.cart_submit_check {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 30rpx;
			.cart_submit_font {
				margin-left: 50rpx;
				color: red;
			}
		}
	}
	.cart_submit_right {
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
</style>
